package se.perp.c4.control;

import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;
import se.perp.c4.control.iface.IMessageReceiver;
import se.perp.c4.net.IConnection;
import se.perp.c4.net.Message;

class MessageWaiter extends SwingWorker<Message, Void> {

    private final IConnection conn;
    private final IMessageReceiver listener;

    public MessageWaiter(IConnection conn, IMessageReceiver listener) {
        this.conn = conn;
        this.listener = listener;
        execute();
    }

    @Override
    protected Message doInBackground() throws Exception {
        return conn.waitForNextMessage();
    }

    @Override
    protected void done() {
        try {
            listener.messageReceived(get());
        } catch (InterruptedException ex) {
            Logger.getLogger(MessageWaiter.class.getName()).log(Level.SEVERE, null, ex);
            listener.messageReceived(null);
        } catch (ExecutionException ex) {
            Logger.getLogger(MessageWaiter.class.getName()).log(Level.SEVERE, null, ex);
            listener.messageReceived(null);
        }
    }
}
